package test_pkg

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

// 互斥锁
type UserInfo struct {
	mu      sync.Mutex
	balance int
}

func update_lock(i *UserInfo, b int) {
	i.mu.Lock()
	i.balance += b
	fmt.Printf("Lock %v\n", i.balance)
	i.mu.Unlock()
	_sleep()

}

func _sleep() {
	rand.Seed(time.Now().UnixNano())
	rand := rand.Intn(10000)
	time.Sleep(time.Duration(rand) * time.Second)
}

func update_unlock(i *UserInfo, b int) {
	i.balance += b
	fmt.Printf("unlock %v\n", i.balance)
	_sleep()

}

func Test_mutex() {
	info := new(UserInfo)
	for i := 0; i < 5; i++ {
		go update_lock(info, 1)
	}

	info1 := new(UserInfo)
	for i := 0; i < 5; i++ {
		go update_unlock(info1, 1)
	}

	time.Sleep(2 * time.Second)

	fmt.Printf("info.balance: %v\n", info.balance)
	fmt.Printf("info1.balance: %v\n", info1.balance)
}
